package com.lenovo.spider.support.cookie;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import lombok.val;
import okhttp3.Cookie;
import okhttp3.HttpUrl;

import java.io.File;
import java.util.List;

import static java.util.stream.Collectors.toList;

/**
 * @author <a href="mailto:liuhan3@lenovo.com">HanL(liuhan3)</a>
 * on 2018/3/29 18:09
 */
public class FileCookieStore implements CookieStore {

    private final File dir;

    public FileCookieStore(String path) {
        if (StrUtil.isAllBlank(path)) {
            this.dir = FileUtil.getUserHomeDir();
        } else if (FileUtil.exist(path) && FileUtil.isDirectory(path)) {
            this.dir = FileUtil.file(path);
        } else {
            this.dir = FileUtil.mkParentDirs(path);
        }
    }

    @Override
    public synchronized void appendCookie(HttpUrl url, List<Cookie> cookies) {
        val cookieFile = getFile(url);
        List<Cookie> cookieList = getCookies(url);
        cookieList.addAll(cookies);
        FileUtil.writeLines(CollUtil.distinct(cookieList), cookieFile, "utf-8");
    }

    @Override
    public List<Cookie> getCookies(HttpUrl url) {
        val cookieFile = getFile(url);
        return FileUtil.readLines(cookieFile, "utf-8").stream()
                .map(str -> Cookie.parse(url, str))
                .distinct()
                .collect(toList());
    }

    private File getFile(HttpUrl url) {
        val domain = url.host();
        File file = FileUtil.file(this.dir, domain);
        if (FileUtil.exist(file)) {
            return file;
        } else {
            return FileUtil.touch(file);
        }
    }

    public static void main(String[] args) {
        val store = new FileCookieStore("");
        List<Cookie> cookieList = CollUtil.newArrayList(new Cookie.Builder()
                .domain("www.baidu.com")
                .name("test")
                .value("test")
                .build());

        cookieList.add(new Cookie.Builder()
                .domain("www.baidu.com")
                .name("test2")
                .value("test")
                .build());

        store.appendCookie(HttpUrl.parse("http://www.baidu.com"), cookieList);

        List<Cookie> cookies = store.getCookies(HttpUrl.parse("http://www.baidu.com"));
        System.out.println(cookies);
    }
}
